/** taro 拦截器封装 */

import Taro from "@tarojs/taro";
import get from 'lodash-es/get'

export interface BasicResponse<T = any> {
  data: T
  msg: string
  status: number
}

const baseUrl = process.env.TARO_APP_BASE_URL

export function taroRequestInterceptor(chain) {
  const requestParams = chain.requestParams;
  const { url } = requestParams;
  
  const transRequestParams = {
    ...requestParams,
    url: url.includes('http://') ? url : baseUrl + url,
  }
  console.log('request ', transRequestParams);

  return chain.proceed(transRequestParams).then(res => {
    console.log('proceed ', res);
    // 响应拦截器
    const { statusCode, data, errMsg } = res;
    if (statusCode !== 200) {
      Taro.showToast({
        title: errMsg || '请求失败',
        icon: 'error'
      })
      return res
    }

    const respCode = get(data, 'status', 1);
    if (respCode === 0) {
      return data
    } else if (respCode === 1) {
      Taro.showToast({
        title: get(data, 'message', '请求失败'),
        icon: 'error'
      })
      return data
    }
    return res
  })
}


Taro.addInterceptor(taroRequestInterceptor);

export function request<T = any>(options: Taro.request.Option) {
  return Taro.request(options) as unknown as Promise<BasicResponse<T>>
}

export default Taro